Skip to main content

tar command

tar - an archiving utility

GNU 'tar' saves many files together into a single tape or disk archive ( generally called as tarball), and can restore individual files from the archive and can optionally compress them.

Usage: tar [OPTION]... [FILE]...

  • OPTION: Flags which enhances the tar abilities. (e.g., create, extract, compress).
  • FILE: The files or directories to include or extract from the tarball.

Examples

  • Creating an Archive

    To bundle files into an archive, use -c (create) and -f (file) options.

    $ tar -cf archive.tar file1.txt file2.txt
    • Creates archive.tar containing file1.txt and file2.txt.
    • -c: Create a new archive.
    • -f: Specify the archive file name.
  • Adding Compression

    Combine -c with a compression flag:

    Gzip Example:

    • -z: Gzip (.tar.gz)
    • -j: Bzip2 (.tar.bz2)
    • -J: Xz (.tar.xz)
    $ tar -czf archive.tar.gz dir1/
    • Creates a compressed archive archive.tar.gz of the dir1 directory.

    Xz Example:

    $ tar -cJf archive.tar.xz dir2/
    • Creates archive.tar.xz with xz compression.
  • Listing Archive Contents

    View what’s inside an archive with -t (list).

    $ tar -tf archive.tar
    • Lists files in archive.tar (e.g., file1.txt file2.txt).

    With Compression:

    $ tar -tzf archive.tar.gz
    • Lists contents of a gzip-compressed archive.
  • Extracting an Archive

    Use -x (extract) to unpack an archive.

    $ tar -xf archive.tar
    • Extracts all files from archive.tar into the current directory.

    With Compression:

    tar -xzf archive.tar.gz
    • Extracts a gzip-compressed archive.

    Specific Files:

    $ tar -xf archive.tar file1.txt
    • Extracts only file1.txt from archive.tar.
  • Extracting to a Directory

    Use -C to extract to a specific directory.

    $ tar -xzf archive.tar.gz -C /tmp/
    • Extracts archive.tar.gz into /tmp/.
  • Verbose Output

    Add -v (verbose) to see what tar is doing.

    $ tar -cvf archive.tar dir1/
    • Shows each file as it’s added (e.g., dir1/file1.txt).

    During Extraction:

    $ tar -xvf archive.tar
    • Lists files as they’re extracted.
$ tar --help